import { StorehouseService } from './../../../@core/services/storehouse/storehouse.service';
import { Component, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { SharedMethodService } from './../../../@core/services/Sharedmethod/shared-method.service';
import { Router } from '@angular/router';
import { UserService } from './../../../@core/services/user/user.service';
import { AddStorehousecategoryComponent } from './storehousecatefory/addstorehousecategory/addstorehousecategory.component';
import { EditStoreHouseCategroyComponent } from './storehousecatefory/edit-store-house-categroy/edit-store-house-categroy.component';
import { AddStoreHouseComponent } from './add-store-house/add-store-house.component';
import { EditStoreHouseComponent } from './edit-store-house/edit-store-house.component';
import { PositiondataComponent } from './positiondata/positiondata.component';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-storehouse',
  templateUrl: './storehouse.component.html',
  styleUrls: ['./storehouse.component.scss']
})
export class StorehouseComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  SearchTerm: string = null;
  pageSizeOptions = [10, 20, 30, 50, 100];
  treeData: any;
  allCheckedStatus = false;
  checkedIds = [];
  deleteIDs = [];
  editemployeeId: ""
  msgs: Array<Object> = [];
  option: any;//部门option
  departmentId: any;//部门id
  pathPids = []//部门树结构路径
  employData: any[] = [];//员工数据
  config = {
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  searchWarehouseCategoryValue: any = ''
  filteredTreeNodes: any
  displayTreeData: any[];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '仓库编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '仓库名称',
        fieldType: 'text',
      },
      {
        field: 'workCode',
        header: '是否允许负库存',
        fieldType: 'boolean'
      },
      {
        field: 'workCode',
        header: '二维码',
        fieldType: 'boolean'
      },
      {
        filed: 'enabled',
        header: '状态',
        fieldType: 'boolean'
      }
    ]
  };//表头数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field: 'name',
      width: '200px'
    },
    {
      field: 'name',
      width: '100px'
    },
    {
      field: 'name',
      width: '100px'
    },
    {
      field: 'name',
      width: '130px'
    },
    {
      field: 'name',
      width: '130px'
    },
    {
      field: 'name',
      width: '100px'
    },
  ];//表格宽度配置
  selectoptions = [
    '全部', '启用', '禁用'
  ]
  selectvalue = '全部'
  tabledata = []
  @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
  @ViewChild(DataTableComponent, { static: true }
  ) datatable!: DataTableComponent;//获取table
  displayTableData: any[];
  Status!: string;
  file: any;
  warehouseCategoryId: any;
  constructor(private dialogService: DialogService, private UserService: UserService, private Router: Router, private SharedMethodService: SharedMethodService, private StorehouseService: StorehouseService) { }
  ngOnInit(): void {
    this.Status = this.selectvalue == '全部' ? "all" : this.selectvalue == '启用' ? "enable" : "disable"
    this.StorehouseService.getWarehouseCategorysWithChildren(1, 999).subscribe((data: any) => {
      this.treeData = data.items
      this.displayTreeData = [{ warehouseCategoryName: '全部', warehouseCategoryId: null }, ...this.treeData];
      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
      if (this.treeData.length > 0) {
        this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
          this.tabledata = data.items;
          this.displayTableData = this.tabledata;
          this.pager.total = data.totalCount;
        })
      }
    })
  }
  afterTreeInit($event: any) {
    if ($event["1"]) {
      $event["1"].data.isActive = true
    }
  }//树形菜单初始化
  getPathPids(node: { warehouseCategoryId: any; subWarehouseCategories: any; }, targetId: any, path = []) {
    if (node.warehouseCategoryId === targetId) {
      return [...path, node.warehouseCategoryId];
    }
    if (node.subWarehouseCategories) {
      for (let subNode of node.subWarehouseCategories) {
        const subPath = this.getPathPids(subNode, targetId, [...path, node.warehouseCategoryId]);
        if (subPath) {
          return subPath;
        }
      }
    }
    return null;
  } //获取树形菜单pid的路径
  nodeSelected($event: any) {
    this.option = $event.data.originItem
    this.warehouseCategoryId = $event.data.originItem.warehouseCategoryId;
    this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata;
      this.pager.total = data.totalCount;
    })
    for (let node of this.treeData) {
      const path = this.getPathPids(node, this.warehouseCategoryId);
      if (path) {
        this.pathPids = path;
        break;
      }else{
        this.pathPids = []
      }
    }
  }//树形菜单点击事件
  CreatDepartment(dialogtype?: string) {
    let data = {
      options: this.treeData,
      pathPids: this.pathPids && this.pathPids[0] !== null ? this.pathPids : [],
      display: false
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '新建仓库类目',
      data: data,
      content: AddStorehousecategoryComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.WarehouseCategory.warehouseCategoryName) {
              this.StorehouseService.createWarehouseCategory(results.modalContentInstance.WarehouseCategory).subscribe((data: any) => {
                this.showToast('success', '成功', '仓库类目创建成功')
                results.modalInstance.hide();
                this.StorehouseService.getWarehouseCategorysWithChildren(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                  this.treeData = data.items
                  this.displayTreeData = [{ warehouseCategoryName: '全部', warehouseCategoryId: null }, ...this.treeData];
                  this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                  this.StorehouseService.getWarehouses(null, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                    this.tabledata = data.items;
                    this.displayTableData = this.tabledata;
                    this.pager.total = data.totalCount;
                  })
                })
              }, (error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              })
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//新建仓库类目
  EditDepartment(dialogtype?: string) {
    if (this.warehouseCategoryId) {
      let data = {
        options: this.treeData,
        pathPids: this.pathPids.slice(0, -1),
        display: false,
        option: this.option
      };
      const results = this.dialogService.open({
        id: 'department',
        ...this.config,
        title: '编辑仓库类目',
        data: data,
        content: EditStoreHouseCategroyComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if (results.modalContentInstance.warehouseCategory.warehouseCategoryName) {
                this.StorehouseService.updateWarehouseCategory(results.modalContentInstance.warehouseCategory, data.option.warehouseCategoryId,).subscribe((data: any) => {
                  this.showToast('success', '成功', '仓库类目编辑成功')
                  results.modalInstance.hide();
                  this.StorehouseService.getWarehouseCategorysWithChildren(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                    this.treeData = data.items
                    this.displayTreeData = [{ warehouseCategoryName: '全部', warehouseCategoryId: null }, ...this.treeData];
                    this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                    this.StorehouseService.getWarehouses(null, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                      this.tabledata = data.items;
                      this.displayTableData = this.tabledata;
                      this.pager.total = data.totalCount;
                    })
                  })
                }, (error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                  results.modalInstance.hide();
                })
              }
              data.display = true;
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }//编辑仓库类目
  DeleteDepartment(dialogtype?: string) {
    if (this.warehouseCategoryId) {
      const results = this.dialogService.open({
        ...this.config,
        title: '删除仓库分类',
        content: '确认删除当前选中的仓库类目？',
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.StorehouseService.deleteWarehouseCategory(this.warehouseCategoryId).subscribe((data: any) => {
                this.showToast('success', '成功', '该仓库类目删除成功')
                results.modalInstance.hide();
                this.StorehouseService.getWarehouseCategorysWithChildren(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                  this.treeData = data.items
                  this.displayTreeData = [{ warehouseCategoryName: '全部', warehouseCategoryId: null }, ...this.treeData];
                  this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                  this.StorehouseService.getWarehouses(null, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                    this.tabledata = data.items;
                    this.displayTableData = this.tabledata;
                    this.pager.total = data.totalCount;
                  })
                })
              }, (error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              }
            )
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }//删除仓库类目
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  searchWarehouseCategory($event: any) {
    this.searchWarehouseCategoryValue = $event.target.value;
    if (this.searchWarehouseCategoryValue === '') {
      // 如果用户输入的值为空，显示原先的数据
      this.displayTreeData = this.displayTreeData = [{ warehouseCategoryName: '全部', warehouseCategoryId: null }, ...this.treeData];
    } else {
      // 否则，显示过滤后的数据
      this.filteredTreeNodes = this.filterCategories(this.treeData, this.searchWarehouseCategoryValue);
      this.displayTreeData = this.filteredTreeNodes;
      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
    }
  }//搜索仓库类目
  pageIndexChange($event: any) {
    this.pager.pageIndex = $event;
    this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata;
      this.pager.total = data.totalCount;
    })
  }//切换页码
  pageSizeChange($event: any) {
    this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata;
      this.pager.total = data.totalCount;
    })
  }//改变每页显示数量
  creatStorehouse(dialogtype?: string) {
    let data = {
      options: this.treeData,
      pathPids: this.pathPids && this.pathPids[0] !== null ? this.pathPids : [],
      display: false
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '新建仓库',
      data: data,
      content: AddStoreHouseComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.stroehouse.warehouseName && results.modalContentInstance.stroehouse.warehouseNum) {
              this.StorehouseService.CreateWarehouse(results.modalContentInstance.stroehouse).subscribe((data: any) => {
                this.showToast('success', '成功', '仓库创建成功')
                results.modalInstance.hide();
                this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                  this.tabledata = data.items;
                  this.displayTableData = this.tabledata;
                  this.pager.total = data.totalCount;
                })
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              })
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//新建仓库
  disabled() {
    this.StorehouseService.disableWarehouses(this.checkedIds).subscribe((data: any) => {
      this.showToast('success', '成功', '禁用成功')
      this.deleteIDs = []
      this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tabledata = data.items;
        this.displayTableData = this.tabledata;
        this.pager.total = data.totalCount;
      })
    }, (error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }//禁用仓库
  enabled() {
    this.StorehouseService.enableWarehouses(this.checkedIds).subscribe((data: any) => {
      this.showToast('success', '成功', '启用成功')
      this.deleteIDs = []
      this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tabledata = data.items;
        this.displayTableData = this.tabledata;
        this.pager.total = data.totalCount;
      })
    }, (error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }//启用仓库
  delete(id: any, dialogtype?: string) {
    const results = this.dialogService.open({
      id: 'department',
      data: { id: id },
      ...this.config,
      title: '删除仓库',
      content: '确认删除当前选中的仓库？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.StorehouseService.deleteWarehouse(id).subscribe((data: any) => {
              this.showToast('success', '成功', '删除成功')
              this.deleteIDs = []
              results.modalInstance.hide();
              this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                this.tabledata = data.items;
                this.displayTableData = this.tabledata;
                this.pager.total = data.totalCount;
              })
            },(error) => {
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
            })
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        }
      ],
    });
  }//删除仓库
  deltes() {
    this.StorehouseService.deleteWarehouses(this.deleteIDs).subscribe((data: any) => {
      this.showToast('success', '成功', '删除成功')
      this.deleteIDs = []
      this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status
        , this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
          this.tabledata = data.items;
          this.displayTableData = this.tabledata;
          this.pager.total = data.totalCount;
        })
    }
      , (error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      })
  }//批量删除
  edit(id: any, dialogtype?: string,) {
    let data = {
      id: id,
      options: this.treeData,
      display: false
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '更新仓库',
      data: data,
      content: EditStoreHouseComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.stroehouse.warehouseName) {
              this.StorehouseService.updateWarehouse(id, results.modalContentInstance.stroehouse).subscribe((data: any) => {
                this.showToast('success', '成功', '仓库更新成功')
                results.modalInstance.hide();
                this.StorehouseService.getWarehouses(null, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                  this.tabledata = data.items;
                  this.displayTableData = this.tabledata;
                  this.pager.total = data.totalCount;
                })
              }, (error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              })
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//编辑仓库
  positionData(rowItem: any, dialogtype?: string) {
    let data = {
      rowItem: rowItem,
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      width: '800px',
      title: '仓位信息',
      data: data,
      content: PositiondataComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//仓位信息
  selctChange() {
    this.Status = this.selectvalue == '全部' ? "all" : this.selectvalue == '启用' ? "enable" : "disable"
    setTimeout(() => {
      this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tabledata = data.items;
        this.displayTableData = this.tabledata;
        this.pager.total = data.totalCount;
      })
    }, 100);
  }//下拉框选择
  search() {
    this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata;
      this.pager.total = data.totalCount;
    })
  }//搜索
  reset() {
    this.Status = null
    this.selectvalue = '全部'
    this.departmentId = null
    this.searchWarehouseCategoryValue = ''
    this.SearchTerm = ''
    this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata;
      this.pager.total = data.totalCount;
    })
  }//重置
  DownloadModel() {
    this.StorehouseService.downloadWarehouseFileModel().subscribe((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '仓库模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载模板
  @ViewChild('fileInput1') fileInput1: any;
  @ViewChild('fileInput2') fileInput2: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput1.nativeElement.click();
  }
  onButtonClick2() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput2.nativeElement.click();
  }
  importFormExcel(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.StorehouseService.importWarehousesFromExcel(this.file).subscribe((data: any) => {
      this.showToast('success', '成功', '导入成功')
      this.StorehouseService.getWarehouses(this.warehouseCategoryId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tabledata = data.items;
        this.displayTableData = this.tabledata;
        this.pager.total = data.totalCount;
      })
    }, (error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }
  DownloadWarehouse() {
    this.StorehouseService.downloadWarehouseFile().subscribe((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '仓库信息.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载员工信息
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable, 'warehouseId').subscribe((data: any) => {
      this.deleteIDs = data;
    })
    this.SharedMethodService.getCheckedRows(this.datatable, 'warehouseId').subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//获取选中行
  cleared() {
    this.SharedMethodService.cleared(this.deleteIDs, this.tabledata, this.datatable).subscribe((data: any) => {
      this.deleteIDs = data;
    })
  }//清空选中行
  DownloadCategoryModel() {
    this.StorehouseService.downloadWarehouseCategoryFileModel().subscribe((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '仓库类型.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载仓库类型模板
  ImportCategory(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.StorehouseService.importWarehouseCategoriesFromExcel(this.file).subscribe((data: any) => {
      this.showToast('success', '成功', '导入成功')
      this.StorehouseService.getWarehouseCategorysWithChildren(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.treeData = data.items
        this.displayTreeData = [{ warehouseCategoryName: '全部', warehouseCategoryId: null }, ...this.treeData];
        this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
        if (this.treeData.length > 0) {
          this.StorehouseService.getAllWarehouses().subscribe((data: any) => {
            this.tabledata = data.items;
            this.displayTableData = this.tabledata;
            this.pager.total = data.totalCount;
          })
        }
      })
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }
  setOpenTrue = (node: { open: boolean; subWarehouseCategories: any[]; }) => {
    // 为当前节点添加 open: true 属性
    node.open = true;
    // 如果当前节点有子节点，递归处理子节点
    if (Array.isArray(node.subWarehouseCategories)) {
      node.subWarehouseCategories = node.subWarehouseCategories.map(this.setOpenTrue);
    }
    return node;
  }
  filterCategories(categories: any[], keyword: string): any[] {
    const result: any[] = [];
    for (const category of categories) {
      if (category.warehouseCategoryName.includes(keyword)) {
        result.push(category);
      }
      if (category.subWarehouseCategories.length > 0) {
        const filteredSubCategories = this.filterCategories(category.subWarehouseCategories, keyword);
        if (filteredSubCategories.length > 0) {
          result.push(...filteredSubCategories);
        }
      }
    }
    return result;
  }
  getImagesArray2(fileURL: string): string[] {
        let urls = fileURL.split(',');
        urls = urls.map(url => environment.modifiedApiUrl +'/' + url);
        return urls;
      }
}
